﻿using MongoDB.Bson;
using MongoDB.Driver;
using System.Threading.Tasks;

namespace Sustainalytics.DataLayer
{
    public static class MongoDatabaseFactory
    {
        public static IMongoDatabase GetDatabase(string connectionString)
        {
            var mongoUrlBuilder = new MongoUrlBuilder(connectionString);
            var settings = MongoClientSettings.FromUrl(mongoUrlBuilder.ToMongoUrl());
            settings.WaitQueueSize = int.MaxValue;
            settings.MinConnectionPoolSize = 1;
            settings.MaxConnectionPoolSize = 100;

            var client = new MongoClient(settings);
            var mongoDatabase = client.GetDatabase(mongoUrlBuilder.DatabaseName);
            return mongoDatabase;
        }
    }

    public static class IMongoDatabaseExtensions
    {
        public static IMongoCollection<T> GetCollection<T>(this IMongoDatabase mongoDatabase, string collectionName = null)
        {
            return mongoDatabase.GetCollection<T>(collectionName ?? typeof(T).Name);
        }

        public static bool CollectionExists(this IMongoDatabase mongoDatabase, string collectionName)
        {
            var filter = new BsonDocument("name", collectionName);
            var collections = mongoDatabase.ListCollections(new ListCollectionsOptions { Filter = filter });
            return collections.Any();
        }

        public async static Task<bool> CollectionExistsAsync(this IMongoDatabase mongoDatabase, string collectionName)
        {
            var filter = new BsonDocument("name", collectionName);
            var collections = await mongoDatabase.ListCollectionsAsync(new ListCollectionsOptions { Filter = filter });
            return await collections.AnyAsync();
        }
    }
}
